#!/usr/bin/perl
use Getopt::Std;
getopt("t:d:i:r:h:o", \%args); 
my $tpedfile = $args{t};
my $dosagefile= $args{d};
my $indicatorfile= $args{i};
my $rsids_3datasets = $args{r};
my $rsids_hapmap3 = $args{h};
my $outdir = $args{o};
chomp $tpedfile;
chomp $dosagefile;
chomp $indicatorfile;
chomp $rsids_3datasets;
chomp $rsids_hapmap3;
chomp($outdir);
#print $outdir."\n";
if($tpedfile eq "")
{
	die "entered tpedfile name is empty\n";
	
}
if($dosagefile eq "")
{
        die "entered dosagefile name  is empty\n";

}
if($indicatorfile eq "")
{
        die "entered indicator file name is empty\n";

}
if($rsids_3datasets eq "")
{
        die "entered rsids 3 datasets filename  is empty\n";

}
if($rsids_hapmap3 eq "")
{
        die "entered rsidshapmap3 file name is empty\n";

}
if($outdir eq "")
{
	die "entered $outdir is empty";

}
#print "Sample : $sample Marker : $marker Reference: $reference Windowsize : $window Edges : $edge\n";
$file1 = "$outdir/final_tped";
print $file1;
open(WRBUFF1,">$file1");
open(WRBUFF2,">$outdir/final_dosage");
open(WRBUFF3,">$outdir/final_ind");
#open(WRBU,">$file1");
#print WRBU "hi\n";
open BUFF,"< $rsids_3datasets" or die "Can't open $rsids_3datasets : $!";
while($line = <BUFF>)
{
	chomp($line);
	if($line =~ m/AFFX/)
        {
                @array = split("_",$line);
                $hash1{$array[@array-1]} =0;
                #print $array[@array-1]."\n";
        }
	else{
	$hash{$line} = 0;
	}
}
open BUFF,"< $rsids_hapmap3" or die "Can't open $rsids_hapmap3 : $!";
while($line = <BUFF>)
{
        chomp($line);
	if($line =~ m/AFFX/)
        {
                @array = split("_",$line);
                $hash1{$array[@array-1]} =1;
                #print $array[@array-1]."\n";
        }
        else{
        $hash{$line} = 1;
	}
}
open BUFF ,"< $tpedfile" or die "Can't open $tpedfile : $!";
while($line = <BUFF>)
{
        chomp($line);
        @tarray = split(/\s/,$line);
	if($tarray[0] != 26)
	{
		if($hash{$tarray[1]} eq "0" || $hash{$tarray[1]} eq "1")
		{
			$hash_st{$tarray[1]} = 1;
		#	print WRBUFF1 $line."\n";
		}
	}
	else
	{
		$hash{$tarray[1]} =2;
	}
}
open BUFF ,"< $dosagefile" or die "Can't open $dosagefile : $!";
#$line = <BUFF>;
#print WRBUFF2 $line;
while($line = <BUFF>)
{
        chomp($line);
        @tarray = split(/\s/,$line);
			if($hash_st{$tarray[0]} == 1)
			{
				$hash_st{$tarray[0]} = 11;
                        print WRBUFF2 $line."\n";
			}
}
open BUFF ,"< $indicatorfile" or die "Can't open $indicatorfile : $!";
#$line = <BUFF>;
#print WRBUFF3 $line;
while($line = <BUFF>)
{
        chomp($line);
        @tarray = split(/\s/,$line);
	if($hash_st{$tarray[0]} == 11)
	{
        	print WRBUFF3 $line."\n";
	}
}

open BUFF ,"< $tpedfile" or die "Can't open $tpedfile : $!";
while($line = <BUFF>)
{
	chomp($line);
        @tarray = split(/\s/,$line);
	if($hash_st{$tarray[1]} == 11)
	{
                print WRBUFF1 $line."\n";
	}
}

